import axios from 'axios'
import { showErrorByStatus } from '../utils/permissionAlert'

// Create axios instance
const api = axios.create({
  baseURL: '/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// Request interceptor
api.interceptors.request.use(
  config => {
    // Add auth token if exists
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Token ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// Response interceptor
api.interceptors.response.use(
  response => {
    // 直接返回data，保持与原有代码的兼容性
    return response.data
  },
  error => {
    console.error('API Error:', error)
    
    if (error.response) {
      const status = error.response.status
      const errorMessage = error.response.data?.error || error.response.data?.detail
      
      // 处理401未授权错误
      if (status === 401) {
        // 清除本地存储的认证信息
        localStorage.removeItem('token')
        localStorage.removeItem('user')
        
        // 如果不在登录页，显示错误提示并跳转
        if (window.location.pathname !== '/login') {
          showErrorByStatus(401, null)
          setTimeout(() => {
            window.location.href = '/login'
          }, 2000)
        }
      }
      // 处理403权限错误
      else if (status === 403) {
        showErrorByStatus(403, errorMessage)
      }
      // 处理404错误
      else if (status === 404) {
        showErrorByStatus(404, errorMessage)
      }
      // 处理500服务器错误
      else if (status === 500) {
        showErrorByStatus(500, errorMessage)
      }
    }
    
    return Promise.reject(error)
  }
)

// API methods
export default {
  // 通用方法
  get: (url, config) => api.get(url, config),
  post: (url, data, config) => api.post(url, data, config),
  put: (url, data, config) => api.put(url, data, config),
  delete: (url, config) => api.delete(url, config),
  
  // Auth
  login: (data) => api.post('/login/', data),
  register: (data) => api.post('/register/', data),
  logout: () => api.post('/logout/'),
  getCurrentUser: () => api.get('/current-user/'),
  updateCurrentUser: (data) => api.patch('/current-user/', data),
  

  // Projects
  getProjects: () => api.get('/projects/'),
  getProject: (id) => api.get(`/projects/${id}/`),
  createProject: (data) => api.post('/projects/', data),
  updateProject: (id, data) => api.put(`/projects/${id}/`, data),
  deleteProject: (id) => api.delete(`/projects/${id}/`),

  // Environments
  getEnvironments: () => api.get('/environments/'),
  getEnvironment: (id) => api.get(`/environments/${id}/`),
  createEnvironment: (data) => api.post('/environments/', data),
  updateEnvironment: (id, data) => api.put(`/environments/${id}/`, data),
  deleteEnvironment: (id) => api.delete(`/environments/${id}/`),

  // Host Groups
  getHostGroups: () => api.get('/host-groups/'),
  getHostGroup: (id) => api.get(`/host-groups/${id}/`),
  createHostGroup: (data) => api.post('/host-groups/', data),
  updateHostGroup: (id, data) => api.put(`/host-groups/${id}/`, data),
  deleteHostGroup: (id) => api.delete(`/host-groups/${id}/`),

  // Hosts
  getHosts: (params) => api.get('/hosts/', { params }),
  getHost: (id) => api.get(`/hosts/${id}/`),
  createHost: (data) => api.post('/hosts/', data),
  updateHost: (id, data) => api.put(`/hosts/${id}/`, data),
  deleteHost: (id) => api.delete(`/hosts/${id}/`),
  getMacAddress: (data) => api.post('/hosts/get_mac_address/', data),
  hostInspection: (data) => api.post('/host-inspection/', data),
  syncHostsStatus: () => api.post('/sync-hosts-status/'),
  hostPowerAction: (id, action) => api.post(`/hosts/${id}/power/`, { action }),
  autoGetMacAddress: (id) => api.post(`/hosts/${id}/auto-get-mac/`),
  testSSHConnection: (id) => api.post(`/hosts/${id}/test-ssh/`),
  downloadFile: (id, remotePath) => {
    // 文件下载需要特殊处理，返回blob
    return axios({
      url: `/api/hosts/${id}/download_file/`,
      method: 'POST',
      data: { remote_path: remotePath },
      responseType: 'blob',
      headers: {
        'Authorization': `Token ${localStorage.getItem('token')}`,
        'Content-Type': 'application/json'
      }
    })
  },
  collectSystemInfo: (id) => api.post(`/hosts/${id}/collect_system_info/`),

  // Email Config
  getEmailConfigs: () => api.get('/email-configs/'),
  createEmailConfig: (data) => api.post('/email-configs/', data),
  updateEmailConfig: (id, data) => api.put(`/email-configs/${id}/`, data),
  deleteEmailConfig: (id) => api.delete(`/email-configs/${id}/`),
  testEmailConfig: (id) => api.post(`/email-configs/${id}/test/`),

  // Users
  getUsers: () => api.get('/users/'),
  getUser: (id) => api.get(`/users/${id}/`),
  createUser: (data) => api.post('/users/', data),
  updateUser: (id, data) => api.put(`/users/${id}/`, data),
  deleteUser: (id) => api.delete(`/users/${id}/`),

  // Groups
  getGroups: () => api.get('/groups/'),
  getGroup: (id) => api.get(`/groups/${id}/`),
  createGroup: (data) => api.post('/groups/', data),
  updateGroup: (id, data) => api.put(`/groups/${id}/`, data),
  deleteGroup: (id) => api.delete(`/groups/${id}/`),

  // Ansible Management
  getInventories: () => api.get('/ansible/inventories/'),
  createInventory: (data) => api.post('/ansible/inventories/', data),
  updateInventory: (id, data) => api.put(`/ansible/inventories/${id}/`, data),
  deleteInventory: (id) => api.delete(`/ansible/inventories/${id}/`),
  getCredentials: () => api.get('/ansible/credentials/'),
  createCredential: (data) => api.post('/ansible/credentials/', data),
  updateCredential: (id, data) => api.put(`/ansible/credentials/${id}/`, data),
  deleteCredential: (id) => api.delete(`/ansible/credentials/${id}/`),
  getPlaybooks: () => api.get('/ansible/playbooks/'),
  getPlaybook: (id) => api.get(`/ansible/playbooks/${id}/`),
  createPlaybook: (data) => api.post('/ansible/playbooks/', data),
  updatePlaybook: (id, data) => api.put(`/ansible/playbooks/${id}/`, data),
  deletePlaybook: (id) => api.delete(`/ansible/playbooks/${id}/`),
  executePlaybook: (id, data) => api.post(`/ansible/playbooks/${id}/execute/`, data),
  executePlaybookContent: (data) => api.post('/ansible/playbooks/execute_content/', data),
  uploadPlaybookToHost: (data) => api.post('/ansible/playbooks/upload_to_host/', data),
  listRemoteFiles: (data) => api.post('/ansible/playbooks/list_remote_files/', data),
  readRemoteFile: (data) => api.post('/ansible/playbooks/read_remote_file/', data),
  syntaxCheck: (data) => api.post('/ansible/playbooks/syntax_check/', data),
  executeAdhoc: (data) => api.post('/ansible/execute-adhoc/', data),
  getJobs: () => api.get('/ansible/jobs/'),
  deleteJob: (id) => api.delete(`/ansible/jobs/${id}/`),
  bulkDeleteJobs: (ids) => api.post('/ansible/jobs/bulk_delete/', { ids }),
  getAnsibleModules: (search) => api.get('/ansible/modules/', { params: { search } }),

  // Audit Logs
  getAuditLogs: (params) => api.get('/audit-logs/', { params }),
  getAuditLog: (id) => api.get(`/audit-logs/${id}/`),
  resolveAuditLog: (id) => api.post(`/audit-logs/${id}/resolve/`),
  getAuditLogStatistics: () => api.get('/audit-logs/statistics/'),
  deleteAuditLog: (id) => api.delete(`/audit-logs/${id}/`),
  bulkResolveAuditLogs: (ids) => {
    const url = '/audit-logs/bulk_resolve/'
    console.log('🔵 批量解决URL:', url)
    return api.post(url, { ids })
  },
  bulkDeleteAuditLogs: (ids) => {
    const url = '/audit-logs/bulk_delete/'
    console.log('🔴 批量删除URL:', url)
    console.log('🔴 完整URL:', `${api.defaults.baseURL}${url}`)
    return api.post(url, { ids })
  },

  // Inspection History
  getInspectionHistory: (params) => api.get('/inspection-history/', { params }),
  getInspectionChartData: (hostId, hours = 24) => api.get('/inspection-history/chart_data/', { 
    params: { host_id: hostId, hours } 
  }),
  getMultiHostChartData: (hostIds, hours = 24) => api.get('/inspection-history/multi_host_chart/', { 
    params: { host_ids: hostIds, hours } 
  }),

  // User Group Management
  getUserGroups: (params) => api.get('/user-management/groups/', { params }),
  getUserGroup: (id) => api.get(`/user-management/groups/${id}/`),
  createUserGroup: (data) => api.post('/user-management/groups/', data),
  updateUserGroup: (id, data) => api.put(`/user-management/groups/${id}/`, data),
  deleteUserGroup: (id) => api.delete(`/user-management/groups/${id}/`),
  addUsersToGroup: (groupId, userIds) => api.post(`/user-management/groups/${groupId}/add_users/`, { user_ids: userIds }),
  removeUsersFromGroup: (groupId, userIds) => api.post(`/user-management/groups/${groupId}/remove_users/`, { user_ids: userIds }),
  getUserGroupStatistics: () => api.get('/user-management/groups/statistics/'),
  
  // User Management
  getAllUsers: (params) => api.get('/user-management/users/', { params }),
  getUserWithGroups: (id) => api.get(`/user-management/users/${id}/`),
  updateUserGroups: (userId, groupIds) => api.post(`/user-management/users/${userId}/update_groups/`, { group_ids: groupIds }),
  
  // Change User Password (for admin)
  changeUserPassword: (userId, data) => api.post(`/users/${userId}/change_password/`, data),
  
  // Role Management
  getRoles: () => api.get('/roles/'),
  getRole: (id) => api.get(`/roles/${id}/`),
  createRole: (data) => api.post('/roles/', data),
  updateRole: (id, data) => api.put(`/roles/${id}/`, data),
  deleteRole: (id) => api.delete(`/roles/${id}/`),
  updateRolePermissions: (id, data) => api.post(`/roles/${id}/permissions/`, data),
  
  // Groups (Django auth.Group for role management)
  getGroups: (params) => api.get('/groups/', { params }),
  getGroup: (id) => api.get(`/groups/${id}/`),
  
  // Permissions
  getCurrentUserPermissions: () => api.get('/current-user-permissions/')
}
